import {createRouter, createWebHistory} from "vue-router";
import bus from "@/bus/mitt.js";
import companyRoute from "@/route/companyRoute.js";
import personRoute from "@/route/personRoute.js";

const routes = [
  {
    path: '/',
    component: () => import('../view/login.vue'),
    name: 'login',
    meta: {
      title: '登录',
      type: 'all'
    }
  },
  {
    path: '/register',
    component: () => import('../view/register.vue'),
    name: 'register',
    meta: {
      title: '注册',
      type: 'all'
    }
  },
  {
    path: '/find',
    component: () => import('../view/findpwd.vue'),
    name: 'findpwd',
    meta: {
      title: '找回密码',
      type: 'all'
    }
  },
  {
    path: '/update',
    component: () => import('../view/updatepwd.vue'),
    name: 'updatepwd',
    meta: {
      title: '更新密码',
      type: 'all'
    }
  },
  {
    path: '/Home',
    component: () => import('../view/home.vue'),
    name: 'Home',
    meta: {
      title: '首页',
      type: 'all'
    },
    children: [
      {
        path: '/Home/dashboard',
        component: () => import('../view/homeView/dashboard.vue'),
        name: 'dashboard',
        meta: {
          title: '工作台',
          arr: ['工作台'],
          type: 'all',
          keepAlive: true
        }
      },
      {
        path: '/Home/test1',
        component: () => import('../view/homeView/test1.vue'),
        name: 'test1',
        meta: {
          title: '测试1',
          arr: ['测试1'],
          type: 'company',
          keepAlive: true
        }
      },
      ...companyRoute,
      ...personRoute

    ]
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_PATH), // 路由类型
  routes
});

let whiteList = ['login', 'register', 'findpwd', 'updatepwd']; // 不需要登录的页面
// 路由前拦截
router.beforeEach((to, from, next) => {
  if (whiteList.indexOf(to.name) !== -1) {
    next();
  } else {
    let token = localStorage.getItem('token');
    let id = localStorage['id'];
    bus.$emit('routeChangeBefore', to);
    if (token && id) {
      next();
    } else {
      next('/');
    }
  }
});

// 路由后拦截
router.afterEach((to, from) => {
  if (whiteList.indexOf(to.name) === -1) {
    // 通知路由变化
    bus.$emit('routeChangeAfter', to);
  }
});


export default router;
